package com.example.Controller;

import com.example.Result.AllResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.security.SecureRandom;
import java.util.Arrays;

@RestController
public class RandomLetterGenerator {
    private static final long VALID_DURATION = 5 * 60 * 1000; // 有效时长，单位为毫秒
    private long generatedTimestamp = 0;
    private String generatedRandomString = null;

    @PostMapping("/getrandom")
    private AllResult createRandom () {
        int length = 6; // 字符串长度
        String characters = "1234567890";//随机字符集

        SecureRandom secureRandom = new SecureRandom();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++) {
            // 从字母字符集中随机选择一个字母
            char randomChar = characters.charAt(secureRandom.nextInt(characters.length()));
            sb.append(randomChar);
        }
        generatedRandomString = sb.toString();
        generatedTimestamp = System.currentTimeMillis();
        System.out.println("验证码: " + generatedRandomString + "," +"发送时间：" + generatedTimestamp);
        return AllResult.allResult(1,"已发送，五分钟内有效！",generatedRandomString);
    }
    @PostMapping("/postrandom")
    private AllResult verify(@RequestBody Object[] arr){
        StringBuilder sb = new StringBuilder();
        for (Object num : arr) {
            sb.append(num);
        }
        String verification = sb.toString();
        long currentTimestamp = System.currentTimeMillis();

        if(currentTimestamp - generatedTimestamp <= VALID_DURATION) {
            if (verification.equals(generatedRandomString)) {
                return AllResult.allResult(1, "success！", null);
            } else {
                return AllResult.allResult(0, "验证失败，请重试！", null);
            }
        } else if(generatedTimestamp == 0 || generatedRandomString == null){
            return AllResult.allResult(0, "请先申请验证码！", null);
        } else {
            return AllResult.allResult(0, "验证码已失效，请重新申请！", null);
        }
    }
}